<template>

  <div class="app-container">
    <!-- 标签切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="正常结果" name="normal"></el-tab-pane>
      <el-tab-pane label="异常结果" name="abnormal"></el-tab-pane>
    </el-tabs>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="信息系统院ID" prop="systemId">
        <el-input
            v-model="queryParams.systemId"
            placeholder="请输入信息系统院ID"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查唯一标识符" prop="risStudyId">
        <el-input
            v-model="queryParams.risStudyId"
            placeholder="请输入检查唯一标识符"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tipList">
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="国家机构编码" align="center" prop="fixmedinsCode" />
      <el-table-column label="信息系统院内唯一ID" align="center" prop="systemId" />
      <el-table-column label="检查唯一标识符" align="center" prop="risStudyId" />

      <!-- API字段列，带状态标识 -->
      <el-table-column
          v-for="field in apiFields"
          :key="field.prop"
          :label="field.label"
          align="center"
          :prop="field.prop"
      >
        <template #default="scope">
          <div class="api-field-cell" @click="handleFieldClick(scope.row, field)">
            <span v-if="scope.row[field.prop]">
              <el-icon class="abnormal-icon" title="有异常"><Warning /></el-icon>
              <!-- 当source为front_service时直接显示异常值 -->
              <span v-if="scope.row.source === 'front_service'" class="abnormal-text">{{ scope.row[field.prop] }}</span>
              <span v-else class="abnormal-text">异常</span>
            </span>
            <span v-else class="normal-text">正常</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'danger' : 'success'">
            {{ scope.row.status === 1 ? '异常' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 多列数据弹窗 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="80%"
        :before-close="handleDialogClose"
    >
      <el-table :data="dialogTableData" v-loading="dialogLoading" style="width: 100%">
        <el-table-column
            v-for="column in dialogColumns"
            :key="column.prop"
            :label="column.label"
            :prop="column.prop"
            :width="column.width"
            :show-overflow-tooltip="true"
        />
      </el-table>
    </el-dialog>

    <!-- 单列数据弹窗 -->
    <el-dialog
        :title="singleColumnDialogTitle"
        v-model="singleColumnDialogVisible"
        width="60%"
        :before-close="handleSingleColumnDialogClose"
    >
      <div class="single-column-dialog-content">
        <div class="single-column-content">{{ singleColumnContent }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning, Search, Refresh } from '@element-plus/icons-vue'
import { listTip, getExceptionDetail } from "@/api/os/tip"

// API字段配置
const API_FIELDS_CONFIG = {
  apiPatientApply: {
    label: '患者申请信息上传',
    apiType: 'patient_apply',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'psnCertType', label: '证件类型', width: 80 },
      { prop: 'certno', label: '证件号码', width: 120 },
      { prop: 'fixmedinsCode', label: '机构代码', width: 100 },
      { prop: 'examItemCode', label: '检查项目代码', width: 120 },
      { prop: 'imgExamItem', label: '检查项目名称', width: 150 },
      { prop: 'appyNo', label: '申请单号', width: 120 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiPatientCheck: {
    label: '患者检查数据上传',
    apiType: 'patient_check',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'examItemCode', label: '检查项目代码', width: 120 },
      { prop: 'imgExamItem', label: '检查项目名称', width: 150 },
      { prop: 'examDate', label: '检查日期', width: 100 },
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiPatientReport: {
    label: '患者报告数据上传',
    apiType: 'patient_report',
    columns: [
      { prop: 'psnName', label: '人员姓名', width: 100 },
      { prop: 'rpotNo', label: '报告编号', width: 120 },
      { prop: 'rptDate', label: '报告日期', width: 120 },
      { prop: 'examRsltCode', label: '检查结果', width: 100 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiReportSnapshot: {
    label: '报告快照PDF上传',
    apiType: 'report_snapshot',
    columns: [
      { prop: 'rpotNo', label: '报告编号', width: 120 },
      { prop: 'snapshotSeriesNumber', label: '快照序号', width: 100 },
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiImageSequence: {
    label: '影像序列信息上报',
    apiType: 'image_sequence',
    columns: [
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'seriesInstanceUid', label: '序列UID', width: 150 },
      { prop: 'seriesNumber', label: '序列号', width: 80 },
      { prop: 'seriesImageCount', label: '影像数量', width: 80 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiImageVideo: {
    label: '影像图像信息上报',
    apiType: 'image_video',
    columns: [
      { prop: 'studyInstanceUid', label: '检查UID', width: 150 },
      { prop: 'seriesInstanceUid', label: '序列UID', width: 150 },
      { prop: 'sopInstanceUid', label: '图像UID', width: 150 },
      { prop: 'keyImageFlag', label: '关键图', width: 80 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiSettlement: {
    label: '结算信息上报',
    apiType: 'settlement',
    columns: [
      { prop: 'hospitalSetNo', label: '结算ID', width: 120 },
      { prop: 'psnName', label: '患者姓名', width: 100 },
      { prop: 'setlType', label: '结算类型', width: 80 },
      { prop: 'projMon', label: '总金额', width: 100 },
      { prop: 'errorMsg', label: '错误信息', width: 200 }
    ]
  },
  apiDicomFile: {
    label: '作废索引数据',
    apiType: 'invalid_index',
    columns: [
      { prop: 'content', label: '作废内容', width: 300 },
      { prop: 'remark', label: '备注', width: 200 }
    ]
  }
}

// 响应式数据
const activeTab = ref('normal')
const loading = ref(true)
const showSearch = ref(true)
const total = ref(0)
const tipList = ref([])
const apiFields = ref(Object.keys(API_FIELDS_CONFIG).map(key => ({
  prop: key,
  label: API_FIELDS_CONFIG[key].label
})))

// 多列弹窗相关
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const dialogTitle = ref('')
const dialogTableData = ref([])
const dialogColumns = ref([])
const currentField = ref(null)
const currentRow = ref(null)

// 单列弹窗相关
const singleColumnDialogVisible = ref(false)
const singleColumnDialogTitle = ref('')
const singleColumnContent = ref('')

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  fixmedinsCode: null,
  systemId: null,
  risStudyId: null,
  status: null,
  source: null
})

// 方法
const getList = () => {
  loading.value = true

  // 构建POST请求参数
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    fixmedinsCode: queryParams.fixmedinsCode,
    systemId: queryParams.systemId,
    risStudyId: queryParams.risStudyId,
    source: queryParams.source
  }
  debugger
  // 根据标签设置状态参数
  if (activeTab.value === 'abnormal') {
    params.status = 1 // 异常
  } else if (activeTab.value === 'normal') {
    params.status = 0 // 正常
    params.source = 'cpower_service' // 只查询最后一步
  }

  // 使用POST请求
  listTip(params).then(response => {
    tipList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

const handleTabClick = (tab) => {
  queryParams.pageNum = 1
  getList()
}

const handleFieldClick = (row, field) => {
  if (!row[field.prop]) {
    return // 正常字段不处理
  }

  currentRow.value = row
  currentField.value = field

  // 判断是否需要请求接口
  const shouldRequestApi = row.source === 'front_service' && field.prop !== 'apiDicomFile';

  if (shouldRequestApi) {
    // 使用GET请求获取异常详情 - 传入id和字段名称
    dialogTitle.value = `${field.label} - 异常详情`
    dialogVisible.value = true
    dialogLoading.value = true

    getExceptionDetail(row.id, field.prop)
        .then(response => {
          dialogTableData.value = response.data || []
          // 使用配置的动态列
          dialogColumns.value = API_FIELDS_CONFIG[field.prop].columns
          dialogLoading.value = false
        })
        .catch(() => {
          // 接口失败时显示配置的列信息，但表格数据为空
          dialogColumns.value = API_FIELDS_CONFIG[field.prop].columns
          dialogTableData.value = []
          dialogLoading.value = false
          ElMessage.error('接口请求失败，无法获取详细数据')
        })
  } else {
    // 直接显示单列内容
    showSingleColumnData(row[field.prop], `${field.label} - 内容详情`)
  }
}

const showSingleColumnData = (content, title) => {
  singleColumnDialogTitle.value = title
  singleColumnDialogVisible.value = true

  if (!content) {
    singleColumnContent.value = '无数据'
    return
  }

  try {
    // 尝试解析JSON
    const data = JSON.parse(content)
    if (typeof data === 'object') {
      // 如果是对象，转换为格式化字符串
      singleColumnContent.value = JSON.stringify(data, null, 2)
    } else {
      formatSingleColumnContent(content)
    }
  } catch (e) {
    formatSingleColumnContent(content)
  }
}

const formatSingleColumnContent = (content) => {
  // 检查是否是分号分隔的键值对
  if (content.includes(';')) {
    const lines = content.split(';').filter(line => line.trim())
    let formattedContent = ''

    lines.forEach(line => {
      const colonIndex = line.indexOf(':')
      if (colonIndex > 0) {
        const key = line.substring(0, colonIndex).trim()
        const value = line.substring(colonIndex + 1).trim()
        formattedContent += `${key}: ${value}\n`
      } else {
        formattedContent += `${line.trim()}\n`
      }
    })

    singleColumnContent.value = formattedContent.trim()
  } else {
    // 普通文本内容
    singleColumnContent.value = content
  }
}

const handleDialogClose = () => {
  dialogVisible.value = false
  dialogTableData.value = []
  dialogColumns.value = []
}

const handleSingleColumnDialogClose = () => {
  singleColumnDialogVisible.value = false
  singleColumnContent.value = ''
}

const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

const resetQuery = () => {
  // 重置查询参数
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    fixmedinsCode: null,
    systemId: null,
    risStudyId: null,
    status: null,
    source: null
  })
  getList()
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style scoped>
.api-field-cell {
  cursor: pointer;
  padding: 8px 0;
}

.api-field-cell:hover {
  background-color: var(--el-color-primary-light-9);
}

.abnormal-icon {
  color: var(--el-color-danger);
  margin-right: 4px;
}

.abnormal-text {
  color: var(--el-color-danger);
  font-weight: bold;
}

.normal-text {
  color: var(--el-color-success);
}

/* 单列弹窗内容的样式 */
.single-column-dialog-content {
  padding: 10px;
}

.single-column-content {
  white-space: pre-wrap;
  word-break: break-all;
  font-family: monospace;
  line-height: 1.5;
  max-height: 60vh;
  overflow-y: auto;
  padding: 15px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  font-size: 14px;
}

/* 弹窗宽度优化 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>